﻿using HY.Common;
using System;
using System.Windows.Input;

namespace WpfApp.ViewModels
{
    internal class CommandViewModel : BindableBase
    {
        public CommandViewModel()
        {
            //第二个参数可以不传，则不加是否可用判断
            AgeReduceCommand = new RelayCommand(AgeReduceAction, CanAgeReduceAction);

            AgeAddCommand = new RelayCommand<int>(AgeAddAction, CanAgeAddAction);
            AgeAddCommand2 = new RelayCommand<int>(AgeAddAction, CanAgeAddAction2);

            MultiValueCommand = new RelayCommand<object>(MultiValueAction, CanMultiValueAction);
        }
        private int _age;
        public int Age
        {
            get => _age;
            set => SetProperty(ref _age, value);
        }

        #region 不传参数
        public ICommand AgeReduceCommand { get; set; }
        public void AgeReduceAction()
        {
            Age--;
        }
        private bool CanAgeReduceAction()
        {
            if (Age <= 0) return false;
            return true;
        }

        #endregion

        #region 传一个参数（包括取消传参数和取消不传参数2种方式）

        public ICommand AgeAddCommand { get; set; }
        public ICommand AgeAddCommand2 { get; set; }

        public void AgeAddAction(int times)
        {
            Age *= Convert.ToInt32(times);
        }
        /// <summary>
        /// 接收参数的取消
        /// </summary>
        /// <returns></returns>
        private bool CanAgeAddAction()
        {
            if (Age >= 20)
            {
                Age = 20;
                return false;
            }
            return true;
        }
        /// <summary>
        /// 不接收参数的取消
        /// </summary>
        /// <param name="times"></param>
        /// <returns></returns>
        private bool CanAgeAddAction2(int times)
        {
            if (Age >= 20)
            {
                Age = 20;
                return false;
            }
            return true;
        }

        #endregion

        #region 传多个参数

        public ICommand MultiValueCommand { get; set; }

        public void MultiValueAction(object obj)
        {
            object[] multiObj = obj as object[];
            //也可以存Window或者DataGrid对象等
            _ = int.TryParse(multiObj[0].ToString(), out int x);
            _ = int.TryParse(multiObj[1].ToString(), out int y);
            Age = x * y;
        }

        private bool CanMultiValueAction(object obj)
        {
            object[] multiObj = obj as object[];
            return int.TryParse(multiObj[0].ToString(), out _) && int.TryParse(multiObj[1].ToString(), out _);
        }

        #endregion
    }
}
